#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/9/29 15:59
# @Author  : SumKids
# @Site    :
# @File    : QTableWidget.py
# @Software: PyCharm
# @Description:

import sys

from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QVBoxLayout, QTableWidget, \
    QTableWidgetItem, QHeaderView
from faker import Faker

'''

'''


class MyWidget(QWidget):

    def __init__(self) -> None:
        super().__init__()
        self.setWindowTitle('QTableWidget')
        self.resize(800, 400)
        # 初始化faker & 构建假数据集合
        self.faker = Faker(locale='zh_CN')
        self.data = [[self.faker.name(), self.faker.address(), self.faker.ascii_free_email(), self.faker.phone_number()]
                     for _ in range(20)]
        print(self.data)

        # DOC: 1.初始化一个20行4列的空表格
        self.table_widget = QTableWidget(20, 4)
        # 也可以这样设置行和列
        # self.table_widget = QTableWidget()
        # self.table_widget.setRowCount(20)
        # self.table_widget.setColumnCount(4)

        # DOC: 2.设置表头 & 表格的伸缩样式
        self.table_widget.setHorizontalHeaderLabels(['姓名', '地址', '邮箱', '手机号'])
        # Stretch 拉伸填充 >>>  表头会占满整个表格宽度
        self.table_widget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        # ResizeToContents >>> 按照内容长度拓展，表头不会占满整个表头的宽度
        # self.table_widget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)



        # DOC: 3.表格添加数据 self.table_widget.setItem
        for row_index, row_arr in enumerate(self.data):
            print(f'第{row_index}行 - {row_arr}')
            for col_index, col_val in enumerate(row_arr):
                # print(f'({row_index}, {col_index}) - {col_val}')
                self.table_widget.setItem(row_index, col_index, QTableWidgetItem(col_val))

        # DOC: 4.获取 & 设置单元格（QTableWidgetItem）的属性
        first_item: QTableWidgetItem = self.table_widget.item(0, 0)
        first_item.setForeground(Qt.GlobalColor.red)    # 设置字体颜色
        first_item.setBackground(Qt.GlobalColor.yellow) # 设置背景色

        # DOC: 5.表头排序（当前版本可能有问题，这个排序放初始化数据之前，会导致数据加载异常；放之后会直接改变数据加载的顺序）
        self.table_widget.setSortingEnabled(False)


        self.sort_btn = QPushButton('开启排序')
        self.get_btn = QPushButton('获取选中')
        self.init_layout()
        self.bind()

    def init_layout(self):
        layout = QVBoxLayout()
        layout.addWidget(self.table_widget)
        layout.addWidget(self.sort_btn)
        layout.addWidget(self.get_btn)
        self.setLayout(layout)

    def bind(self):
        # DOC: 6. QTableWidget事件
        # 单元格点击
        self.table_widget.cellClicked.connect(lambda row, column: print(f'1. cellClicked：点击单元格({row}, {column})'))
        # 单元格内容发送变化
        self.table_widget.cellChanged.connect(lambda row, column: print(f'2. cellChanged：变化单元格({row}, {column})'))
        self.table_widget.itemChanged.connect(lambda item: print(f'3. itemChanged: ({item.row()}, {item.column()}) - {item.text()}'))
        # self.table_widget.itemDoubleClicked.connect()

        self.sort_btn.clicked.connect(lambda: self.table_widget.setSortingEnabled(True))
        self.get_btn.clicked.connect(lambda: print(f'获取到选中单元格：{self.table_widget.selectedItems()}'))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWidget()
    window.show()
    app.exec()
